import VueRouter from 'vue-router'
import routes from './routers'
import store from '../store'
import Vue from 'vue'
import {
    getUser,
    getToken,
    setToken,
    setMenucode
} from '../utils/common'
import {
    message
} from '@/utils/resetMessage';
//页面加载精度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
Vue.use(VueRouter);

const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return routerPush.call(this, location).catch(error => error)
}

const router = new VueRouter({
    routes,
    mode: 'hash',
    scrollBehavior: () => ({
        y: 0
    }),
});

NProgress.configure({
    showSpinner: false
});

// 页面常量
const LOGIN_PAGE_NAME = '/login';
/**
 * 路由跳转前的操作
 */
router.beforeEach((to, from, next) => {
    NProgress.start();
    //处理老OA跳转过来的参数 兼容老系统  待老系统全面更替后 方可删除
    let query = to.query;
    if ("token" in query) {
        setMenucode(to.meta.module)
        store.dispatch("deleteAdminAllPageTag");
        setToken({
            token: query.token,
            expires_in: 3600,
        });
        if ('authority' in to.meta) {
            if (to.meta.authority) {
                //获取页面按钮权限
                store.dispatch("getAuthority").then(res => {
                    next();
                }).catch(() => {
                    next();
                })
            } else {
                next();
            }
        } else {
            next();
        }
        return
    }


    if (to.path == LOGIN_PAGE_NAME) {
        next();
    } else {
        if (getToken()) {
            if (to.name == 'home') {
                setMenucode(to.meta.module)
            }
            if ('authority' in to.meta) {
                if (to.meta.authority) {
                    setMenucode(to.meta.module)
                    //获取页面按钮权限
                    store.dispatch("getAuthority").then(res => {
                        next();
                    }).catch(() => {
                        next();
                    })
                } else {
                    next();
                }
            } else {
                next();
            }
        } else {
            next(LOGIN_PAGE_NAME);
        }
    }
});


/**
 * 路由跳转后的操作
 */
router.afterEach((to, from) => {
    NProgress.done();
});

export default router